#!/bin/bash

if test -f /home/saltcorn/.config/.saltcorn; then 
    echo "config file already exists"
    exit 0
fi


pg_pass=$(openssl rand -base64 16)
session_secret=$(openssl rand -base64 16)
jwt_secret=$(openssl rand -hex 64)
sudo -iu postgres psql -U postgres -c "ALTER USER saltcorn WITH PASSWORD '${pg_pass}';"

cat <<EOF > /home/saltcorn/.config/.saltcorn
{
    "host":"localhost",
    "port":5432,
    "database":"saltcorn",
    "user":"saltcorn",
    "password":"${pg_pass}",
    "session_secret":"${session_secret}",
    "jwt_secret":"${jwt_secret}",
    "multi_tenant": false
}
EOF
chown saltcorn:saltcorn /home/saltcorn/.config/.saltcorn
chmod 600 /home/saltcorn/.config/.saltcorn
sudo -iu saltcorn /home/saltcorn/.local/bin/saltcorn reset-schema -f
sudo -iu postgres psql -U postgres -d saltcorn -c 'create extension if not exists "uuid-ossp";'
systemctl daemon-reload
systemctl start saltcorn
systemctl enable saltcorn